//原生交互
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_boost/flutter_boost.dart';

class NativeMessagePage extends StatefulWidget {
  const NativeMessagePage({super.key, required this.title});

  final String title;

  @override
  State<NativeMessagePage> createState() => _NativeMessagePageState();
}

class _NativeMessagePageState extends State<NativeMessagePage> with SingleTickerProviderStateMixin {
  int _counter = 0;
  bool isOpen = false;
  late AnimationController _controller;
  late Animation<double> _animation;

  // 创建 MethodChannel（通道名称必须与原生端一致）
  final MethodChannel _channel = MethodChannel('samples.flutter.dev/MethodChannel');
  final EventChannel _eventChannel = EventChannel('samples.flutter.dev/EventChannel');
  final BasicMessageChannel _basicMessageChannel = BasicMessageChannel('samples.flutter.dev/BasicMessageChannel', StandardMessageCodec());

  @override
  void initState() {
    super.initState();
    // BoostChannel.instance.sendEventToNative("eventToNative",{"key1":"value1"});
    _controller = AnimationController(
      duration: const Duration(seconds: 1),
      vsync: this,
    );
    _channel.setMethodCallHandler((call) {
      if (call.method == "getDartData1") {
        print("call.arguments:${call.arguments}");
        return Future.value("ddddddd");
      }
      return Future.value("no");
    });
    _eventChannel.receiveBroadcastStream().listen((data) {
      print("EventChannel Flutter 收到数据:$data");
    });
    _animation = Tween<double>(begin: 50, end: 300).animate(CurvedAnimation(parent: _controller, curve: Curves.bounceOut));

    ///声明一个用来存回调的对象
    // VoidCallback removeListener;

    ///添加事件响应者,监听native发往flutter端的事件
    // removeListener = BoostChannel.instance.addEventListener("yourEventKey", (key, arguments) {
    //   return Future.value("no");
    //
    //   ///deal with your event here
    // });

    ///然后在退出的时候（比如dispose中）移除监听者
    // removeListener.call();

    // BoostChannel.instance.sendEventToNative("eventToNative", {"key1": "value1"});
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _incrementCounter() {
    if (_controller.isAnimating) {
      _controller.stop();
    } else {
      _controller.repeat(reverse: true);
    }
    setState(() {
      _counter++;
      isOpen = !isOpen;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          spacing: 10,
          children: <Widget>[
            const Text(
              """MethodChannel	双向方法调用（最常用）	Dart ↔ 原生
EventChannel	原生到 Dart 的持续事件流（如传感器）	原生 → Dart
BasicMessageChannel	简单数据传递（使用编解码器）	Dart ↔ 原生
""",
            ),
            FilledButton(
              onPressed: () async {
                final value = await _channel.invokeMethod('getData1', {'name': '张三', 'age': 18});
                print("value:$value");
              },
              child: Text("MethodChannel"),
            ),
            FilledButton(
              onPressed: () async {
                final value = await _basicMessageChannel.send({'name': '张三', 'age': 18});
                print("value:$value");
              },
              child: Text("BasicMessageChannel"),
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
